package com.ikingtech.framework.sdk.cluster.node;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ikingtech.framework.sdk.utils.Tools;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author tie yan
 */
@Component
@RequiredArgsConstructor
public class ClusterNodeManager {

    private final Cache<String, ClusterNode> clusterNodeCache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build();

    public void put(ClusterNode node) {
        node.setLastUpdateTimestamp(System.currentTimeMillis());
        this.clusterNodeCache.put(Tools.Str.join(node.getAddress(), node.getPort().toString(), ":"), node);
    }

    public ClusterNode get(String address, Integer port) {
        return this.clusterNodeCache.getIfPresent(Tools.Str.join(address, port.toString(), ":"));
    }

    public List<ClusterNode> getAll() {
        return new ArrayList<>(this.clusterNodeCache.asMap().values());
    }

    public void putAll(Map<String, ClusterNode> clusterNodeMap) {
        this.clusterNodeCache.putAll(clusterNodeMap);
    }
}
